﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Threading.Tasks;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OL.FrameCore.Application;
using OL.FrameCore.Infrastructure.Code;
using OL.FrameCore.Infrastructure.UnitOfWork;
using OL.FrameCore.Repository.EF;
using OL.FrameCore.WebUI.Code;
using UEditorNetCore;

namespace OL.FrameCore.WebUI
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        //public Autofac.IContainer ApplicationContainer { get; private set; }
        //autofac 新增
        public void ConfigureContainer(ContainerBuilder containerBuilder)
        {
            //containerBuilder.RegisterModule<ConfigureAutofac>();

            //containerBuilder.RegisterType<UserService>().As<IUserService>();

            var baseType = typeof(IAutoInject);
            var assemblyApplication = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("OL.FrameCore.Application"));
            var assemblyDomain = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("OL.FrameCore.Domain"));
            var assemblyRepository = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("OL.FrameCore.Repository.EF"));
            containerBuilder.RegisterAssemblyTypes(assemblyApplication, assemblyDomain, assemblyRepository).AsImplementedInterfaces();

            var controllersTypesInAssembly = typeof(Startup).Assembly.GetExportedTypes()
.Where(t => baseType.IsAssignableFrom(t) && t != baseType).ToArray();
            containerBuilder.RegisterTypes(controllersTypesInAssembly).PropertiesAutowired();
        }

        public static readonly ILoggerFactory efLogger = LoggerFactory.Create(builder =>
        {
#if DEBUG
            builder
            .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
            .AddConsole();
#endif
        });


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //添加认证Cookie信息
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
             .AddCookie(options =>
             {
                 options.LoginPath = new PathString("/home/login");//登录路径
                 options.AccessDeniedPath = new PathString("/home/denied");
             });

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //写库
            services.AddDbContext<DefaultDataContext>(optons =>
            {
                string connectString = Configuration["DefaultConnectionString"];
                optons.UseSqlServer(connectString,b=>b.UseRowNumberForPaging()).UseLoggerFactory(efLogger);
            }).AddUnitOfWork<DefaultDataContext>();
            //读库
            services.AddDbContext<ReadOnlyDataContext>(optons =>
            {
                string connectString = Configuration["ReadOnlyConnectionString"];
                optons.UseSqlServer(connectString, b => b.UseRowNumberForPaging());
            }).AddReadUnitOfWork<ReadOnlyDataContext>();



            //services.AddMvc(option =>
            //{
            //    option.Filters.Add(typeof(GlobalExceptionFilter));
            //    //option.Filters.Add(typeof(VisitFilterAttribute));
            //}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddControllersWithViews(
                option =>
                {
                    option.Filters.Add(typeof(GlobalExceptionFilter));
                }
                ).AddRazorRuntimeCompilation();

            //ueditor服务
            services.AddUEditorService("UeditorConfig.json", false);

            //services.AddCacheRepositoryScoped();
            ////services.AddEFSQLServerRepositoryScoped();
            //services.AddServiceScoped();
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped<VisitFilterAttribute>();

            ////依赖注入 使用autofac
            //var builder = new ContainerBuilder();
            //builder.Populate(services);
            //var baseType = typeof(IAutoInject);
            ////var assembly = Assembly.GetEntryAssembly();
            //var assemblyApplication = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("OL.FrameCore.Application"));
            //var assemblyDomain = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("OL.FrameCore.Domain"));
            ////var assemblyRepository = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("OL.FrameCore.Repository.Memory"));
            //var assemblyRepository = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("OL.FrameCore.Repository.EF"));
            //builder.RegisterAssemblyTypes(assemblyApplication, assemblyDomain, assemblyRepository)
            //                .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
            //                .AsImplementedInterfaces().InstancePerLifetimeScope();
            //this.ApplicationContainer = builder.Build();
            //return new AutofacServiceProvider(this.ApplicationContainer);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();

            //验证中间件
            app.UseAuthentication();

            //app.UseMvc(routes =>
            //{
            //    routes.MapRoute(
            //        name: "default",
            //        template: "{controller=Home}/{action=Index}/{id?}");
            //});

            app.UseRouting();
            
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
